import { request } from '@umijs/max';
import { METHOD_TYPE, MODULES } from '@/options';
import * as queryString from 'querystring';
import { Result } from '@/types/common/request';

type DateType = USER_TYPE.LoginRet;
const ApiUrl = {
  LOGIN: `/${MODULES.AUTH}/token`,
  LOGOUT: `/${MODULES.AUTH}/logout`,
  CODE: `/${MODULES.AUTH}/code`,
  UPDATE_RESOURCE: `/${MODULES.AUTH}/updateResource`,
};

/** 获取验证码 */
export async function getCode(options?: { [key: string]: any }) {
  return request<Result<USER_TYPE.Code>>(ApiUrl.CODE, {
    method: METHOD_TYPE.GET,
    headers: {
      'Content-Type': 'application/json',
    },
    ...{
      token: false,
      ...options,
    },
  });
}

/** 登录 */
export async function login(body: USER_TYPE.LoginParams, options?: { [key: string]: any }) {
  const data = queryString.stringify(body);
  return request<Result<DateType>>(ApiUrl.LOGIN, {
    method: METHOD_TYPE.POST,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    data,
    ...{
      token: false,
      ...options,
    },
  });
}

/** 退出登录 */
export async function logout(options?: { [key: string]: any }) {
  return request<Result<string>>(ApiUrl.LOGOUT, {
    method: METHOD_TYPE.GET,
    ...(options || {}),
  });
}

/** 更新权限缓存 */
export async function updateResource(options?: { [key: string]: any }) {
  return request<Result<string>>(ApiUrl.UPDATE_RESOURCE, {
    method: METHOD_TYPE.GET,
    ...(options || {}),
  });
}
